package cc.cc4414.cc02.system.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import cc.cc4414.cc02.system.entity.Role;

/**
 * @author cc 2018年6月12日
 */
public interface RoleRepository extends JpaRepository<Role, Long> {
	Role findByName(String name);

	/**
	 * 删除id为roleId的角色的所有权限
	 * 
	 * @param roleId
	 *            角色id
	 */
	@Modifying
	@Query(value = "delete from role_authority where role_id = ?", nativeQuery = true)
	void deleteRoleAuthorityByRoleId(Long roleId);

	/**
	 * 删除所有用户的roleId角色
	 * 
	 * @param roleId
	 *            角色id
	 */
	@Modifying
	@Query(value = "delete from user_role where role_id = ?", nativeQuery = true)
	void deleteUserRoleByRoleId(Long roleId);

	/**
	 * 为角色roleId赋予权限authorityId
	 * 
	 * @param roleId
	 *            角色id
	 * @param authorityId
	 *            权限id
	 */
	@Modifying
	@Query(value = "insert into role_authority (role_id, authority_id) values (?1, ?2)", nativeQuery = true)
	void saveRoleAuthorityByRoleIdAndAuthorityId(Long roleId, Long authorityId);

	/**
	 * 通过用户id查找该用户拥有的角色
	 * 
	 * @param userId
	 *            用户id
	 * @return 该用户拥有的角色
	 */
	@Query(value = "select r.* from role r, user_role ur where ur.user_id = ? and ur.role_id = r.id", nativeQuery = true)
	List<Role> findByUserId(Long userId);
}
